// pages/memberCenter/getGift/index.js
const {
  MemberModel
} = require('../../../utils/member-model.js');
const utils =
  require("../../../utils/util.js")
const memberModel = new MemberModel();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    type: 1, // 0-已领取，1-未领取
    page: 1,
    pageSize: 10,
    gifts: [],
    beforeGifts: [],
    totalCount: 0,
    isLoadData: false,
    loadText: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getGiftList().then(data => {
      this.setData({
        gifts: this.data.gifts.concat(data.data),
        totalCount: data.totalCount
      })
    })
  },

  getGiftList () {
    const merchantId = wx.getStorageSync('merchantId')
    const memberId = wx.getStorageSync('memberId')
    return new Promise((resolve, reject) => {
      memberModel.getGiftList({
        merchantId,
        memberId,
        receiveChannel: 1,
        queryType: this.data.type,
        limit: this.data.pageSize,
        offset: (this.data.page - 1) * this.data.pageSize
      }).then(data => {
        this.setData({
          beforeGifts: JSON.parse(JSON.stringify(this.data.beforeGifts.concat(data.data)))
        })
        const lists = data.data.map(item => {
          const gift = item.giftDetail.map(item => {
            let promotionAmount = ''
            if (item.giftType == 0) {
              promotionAmount = item.promotionAmount ? utils.formatCurrency(item.promotionAmount, 2) : '0.00'
            } else if (item.giftType == 1) {
              promotionAmount = (item.promotionAmount || 0).toFixed(1)
            } else if (item.giftType == 2) {
              promotionAmount = (item.promotionAmount || 0).toFixed(0)
            } else if (item.giftType == 3) {
              promotionAmount = item.promotionAmount || ''
            }
            const split = promotionAmount.split('.')
            item.couponName = item.couponName || '-'
            item.startTime = item.startTime ? item.startTime.replace(/-/g, "/") : ''
            item.endTime = item.endTime ? item.endTime.replace(/-/g, "/") : ''
            item.promotionAmount = promotionAmount
            item.integer = split[0]
            item.decimals = split[1]
            item.giftType = item.giftType || ''
            item.accumAmount = item.accumAmount || 0
            item.maxAmount = item.maxAmount || 0
            item.discountLimit = item.discountLimit || 0
            item.channels = item.channels || ''
            return {
              ...item
            }
          })
          return {
            availableTime: item.availableTime ? item.availableTime.replace(/-/g, ".").substr(0, 10) : '',
            receiveTime: item.receiveTime ? item.receiveTime.replace(/-/g, ".").substr(0, 10) : '',
            giftDetail: gift,
            orderCode: item.orderCode,
            receiveFlag: item.receiveFlag,
            receiveHideFlag: item.receiveHideFlag,
            receiveChannel: item.receiveChannel
          }
        })
        resolve({
          data: lists,
          totalCount: data.totalCount
        })
      }).catch(err => {
        wx.showToast({
          title: `${err.error}`,
          icon: 'none'
        })
      })
    })
  },

  selectStateCoupon (e) {
    const type = +e.currentTarget.dataset.type;
    if (type != this.data.type) {
      this.setData({
        type,
        gifts: [],
        beforeGifts: [],
        page: 1,
        totalCount: 0
      })
      this.getGiftList().then(data => {
        this.setData({
          gifts: this.data.gifts.concat(data.data),
          totalCount: data.totalCount,
          isLoadData: false
        })
      })
    }
  },

  getGift(e) {
    const {
      index
    } = e.currentTarget.dataset
    const item = this.data.beforeGifts[index]
    if (item.receiveFlag) {
      const merchantId = wx.getStorageSync('merchantId')
      const memberId = wx.getStorageSync('memberId')
      memberModel.takeGift({
        merchantId,
        memberId,
        availableTime: item.availableTime,
        orderCode: item.orderCode,
        shopId: item.shopId,
        giftDetailVOList: item.giftDetail
      }).then(() => {
        wx.showToast({
          title: '领取成功！',
          icon: 'none'
        })
        this.setData({
          gifts: [],
          beforeGifts: [],
          page: 1,
          totalCount: 0
        })
        this.getGiftList().then(data => {
          this.setData({
            gifts: this.data.gifts.concat(data.data),
            totalCount: data.totalCount
          })
        })
      }).catch(err => {
        wx.showToast({
          title: `${err.error}`,
          icon: 'none'
        })
      })
    }
  },

  scrollEnd() {
    let num = [...new Set(this.data.gifts.map(item => item.orderCode))].length
    if (num >= this.data.totalCount) {
      this.setData({
        isLoadData: true,
        loadText: "已经到底了"
      })
    } else {
      this.setData({
        page: this.data.page + 1,
        isLoadData: true,
        loadText: "加载中..."
      })
      this.getGiftList().then(data => {
        this.setData({
          gifts: this.data.gifts.concat(data.data),
          totalCount: data.totalCount
        })
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})